/*
 * AGENT SHERPA
 *  
 * Assignement 2 of the Agent Oriented Software Engineering Course
 * M.Sc. in Advanced Software Engineering (Part-time)
 * University College Dublin www.ucd.ie
 *
 * Copyright (c) 2007 Chris Walsh, Aidan Morrisy and Iain Hull.
 * All rights reserved.
 * 
 * Filename: Main.aps
 * Author:   iain
 * Date:     06 February 2008
 */

package org.agentsherpa.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.Timer;

import org.agentsherpa.model.Drone;
import org.agentsherpa.model.GlobalMap;
import org.agentsherpa.model.MapLoadException;
import org.agentsherpa.model.MapProperties;
import org.agentsherpa.model.MapPropertiesException;
import org.agentsherpa.model.SimulatorModel;

public class MapWindow extends JFrame implements Observer {
    private static final long serialVersionUID = 1168737694067037750L;
	private MapComponent map;
	private JTextField discoveredText = createTextField();
	private JTextField clearedText = createTextField();
	private JTextField totalText = createTextField();
	private JTextField percentText = createTextField();
	private JTextField utilityText = createTextField();
	private SimulatorModel simulator;
	private int totalCount;
	private List<Drone> drones = new ArrayList<Drone>();
	private Timer timer = new Timer(1000, new TimerActionListener() );
	
	
	private class TimerActionListener implements ActionListener {
		private int time = 0;
		private List<Drone> drones = new ArrayList<Drone>();
		private FileWriter file;
		
		TimerActionListener() {
			try {
				file = new FileWriter("Utility.csv");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		public void actionPerformed(ActionEvent e) {
	    	drones.clear();
	    	simulator.getDrones(drones);
			if (file == null || (time == 0 && drones.isEmpty()))
				return;
			
	    	for (Drone drone : drones) {
	    		if (drone.getName().equals("commandcontrol"))
	    			continue;
	    		
	    		try {
					file.write(time + "," + drone.getName() + "," + drone.utility() + "\n");
					file.flush();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
	    	}
	    	time++;
		}
	}

    public MapWindow(SimulatorModel simulator, int zoom, URL backgroundImage) {
    	this.simulator = simulator;
    	simulator.addObserver(this);
    	
    	this.totalCount = simulator.getMap().getRoadPoints().size();
        this.setLayout(new BorderLayout());
        this.map = new MapComponent(simulator, zoom, backgroundImage);
        JScrollPane scroll = new JScrollPane(this.map);
        this.add(scroll, BorderLayout.CENTER);
        JPanel panel = new JPanel();

    	this.totalText.setText(Integer.toString(totalCount));
    	
        panel.add(new JLabel("Discovered:"));
        panel.add(this.discoveredText);
        panel.add(new JLabel("Cleared:"));
        panel.add(this.clearedText);
        panel.add(new JLabel("Total:"));
        panel.add(this.totalText);
        panel.add(new JLabel("Percentage:"));
        panel.add(this.percentText);
        panel.add(new JLabel("Utility:"));
        panel.add(this.utilityText);
        this.add(panel, BorderLayout.NORTH);
        
        this.setSize(map.getPreferredSize());
        //this.setSize(new Dimension(400, 400));
        this.setTitle("Sherpa Map");
        
        this.timer.start();
    }


	private static JTextField createTextField() {
		JTextField text = new JTextField();
        text.setEditable(false);
        //text.setText("          ");
        text.setColumns(7);
        return text;
	}
    
    
    public void update(Observable o, Object arg) {
    	//System.out.println("MapWindow.update");
    	
    	this.discoveredText.setText(Integer.toString(simulator.totalSensed()));
    	this.clearedText.setText(Integer.toString(simulator.totalCleared()));
    	this.percentText.setText(Integer.toString((simulator.totalCleared() * 100) / totalCount)+"%");
    	
    	drones.clear();
    	simulator.getDrones(drones);
    	float totalUtility = 0;
    	int count = 0;
    	StringBuffer tooltip = new StringBuffer("<html>");
    	for (Drone drone : drones) {
    		if (drone.getName().equals("commandcontrol"))
    			continue;
    		
    		totalUtility += drone.utility();
    		tooltip.append(drone.getName()).append(": ").append(drone.utility()).append("<br>");
    		count++;
    	}
    	this.utilityText.setText(Float.toString(totalUtility / drones.size()));
    	this.utilityText.setToolTipText(tooltip.toString());
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MapProperties props = new MapProperties("src/org/agentsherpa/model/faluja.properties");
//                    MapProperties props = new MapProperties("src/org/agentsherpa/model/simple.properties");
                    GlobalMap map = new GlobalMap(props.getMapImageFile());
                    SimulatorModel simulator = new SimulatorModel(map);
                    MapWindow win = new MapWindow(simulator, props.getZoom(), props.getBackgroundImageFile());
                    win.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    win.setVisible(true);
                }
                catch (MapLoadException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (MapPropertiesException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

}
